# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(gbm)
library(caret)
library(tidyverse)
library(readxl)
library(writexl)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "data.xlsx", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.xlsx", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

sampleInfo <- read_xlsx(opt$g) %>%
  rename(ClassNote = Group) %>%
  select(c("SampleID", "ClassNote"))

data <-read_xlsx(opt$i) %>%
  rename(Metabolite = SampleID) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame() %>%
  column_to_rownames("SampleID")

x <- data %>% select(-c("ClassNote"))
y <- data$ClassNote

configData <- read_tsv(opt$config, col_names = F) %>%
  set_colnames(c("arg", "value"))
k <- configGet(configData, "k") %>%
  as.numeric()
k
flds <- createFolds(y = y, k = k)

classNoteIsEnoughs <- y %>%
  unique() %>%
  map_lgl(function(classNote) {
    inData <- data %>%
      filter(ClassNote == classNote)
    nrow(inData) >= k
  })
if (!all(classNoteIsEnoughs)) {
  stop("无法将所有组进行合理的拆分（使每一Fold都包含两组，可降低K值再次尝试）！")
}

valids <- (1:k) %>%
  map_lgl(function(k) {
    classNotes <- y[flds[[k]]]
    classNotes %>%
      unique() %>%
      length() >= 2
  })
while (!all(valids)) {
  seed <- seed + 1
  set.seed(seed)
  flds <- createFolds(y = y, k = k)
  valids <- (1:k) %>%
    map_lgl(function(k) {
      classNotes <- y[flds[[k]]]
      classNotes %>%
        unique() %>%
        length() >= 2
    })
}
save(flds, k, file = "folds.RData")















